(function() {
    'use strict';

    angular.module('weApp.controllers')

            /**
             * 查询页面
             * @param  {[type]} $scope              [description]
             * @param  {[type]} $rootScope          [description]
             * @param  {[type]} $state              [description]
             * @param  {[type]} $timeout            [description]
             * @param  {[type]} $http               [description]
             * @param  {[type]} weAppDataBase       [description]
             * @param  {[type]} $ionicPopup         [description]
             * @param  {[type]} $compile            [description]
             * @param  {[type]} showLinePageService [description]
             * @return {[type]}                     [description]
             */
            .controller('searchCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', '$ionicPopup', '$compile', 'showLinePageService', 'localStorageService',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, $ionicPopup, $compile, showLinePageService, localStorageService) {


                    //设置一个键入延迟
                    var keyUpTimeout = null;

                    //查询历史
                    //TODO
                    $scope.searchContext = {
                        keyUpToSearch: false,
                        searchText: ''
                    }


                    $scope.$on("$ionicView.beforeEnter", function(event, data) {

                        if (localStorageService.get("searchHistory") !== null) {
                            $scope.searchHistory = localStorageService.get("searchHistory") == null ? [] : JSON.parse(localStorageService.get("searchHistory")).reverse();
                        } else {
                            localStorageService.set("searchHistory", null);
                        }

                    });

                    /**
                     * 自动focus 搜索输入框
                     *  在移动版safari(iPhone)上不支持
                     */
                    $scope.$on("$ionicView.enter", function(event, data) {
                        setTimeout(function() {
                            $("#searchInput").focus();
                        }, 10)
                    })

                    /**
                     * 输入关键字查询
                     * @return {[type]} [description]
                     */
                    $scope.searchLine = function() {
                        if (keyUpTimeout)
                            $timeout.cancel(keyUpTimeout);
                        keyUpTimeout = $timeout(function() {
                            $scope.searchContext.keyUpToSearch = true;
                            $scope.keyupResult = [];
                            if ($scope.searchContext.searchText != "") {
                                weAppDataBase.query($rootScope.cityCode, $scope.searchContext.searchText)
                                        .then(function(result) {
                                            angular.element("#keyup-search-list").empty();
                                            if (result.length) {
                                                for (var i = 0; i < result.length; i++) {
                                                    /**
                                                     * 这里取WebSQL回传的值必须已 rows.item(i) 的方式进行读取！
                                                     * 如果已 rows[i] 的方式读取，在chrome(Android)下正常，但在safari(iPhone)下则会报错！
                                                     * @type {[type]}
                                                     */
                                                    var me = result.item(i);
                                                    var stringMe = JSON.stringify(result.item(i));
                                                    //不能输出空字符
                                                    if ($.trim(stringMe) != "") {
                                                        var li = $compile("<li ng-click='showSearchResult(" + stringMe + ",$event);'>" + me.lineName + "</li>")($scope);
                                                        li.appendTo("#keyup-search-list");
                                                    }
                                                }
                                            } else {
                                                var li = angular.element("<li class='gray'>未查询到该线路或站点</li>");
                                                li.appendTo("#keyup-search-list");
                                            }
                                        });
                            } else {
                                angular.element("#keyup-search-list").empty();
                                $scope.keyupResult = [];
                            }
                        }, 300);

                    }

                    /**
                     * 打开线路详细页面（直线图页面）点击事件
                     * @param  {[type]} line  [线路JSON Data]
                     * @param  {[type]} event [当前点击的 event 对象]
                     */
                    $scope.clickSearch = function() {
                        var txt = $scope.searchContext.searchText;
                        if (txt) {
                            $state.go('searchRes', {searchText: txt});
                        }
                    };
                    $scope.showSearchResult = function(line, event) {
                        sessionStorage.setItem("nowLineName", line.lineName);
                        sessionStorage.setItem("clickLine", JSON.stringify(line));
                        $state.go('searchRes', {searchText: line.lineName});
                    };

                    $scope.searchHistoryLine = function(lineName) {
                        sessionStorage.setItem("nowLineName", lineName);
                        sessionStorage.setItem("clickLine", null);
                        $state.go('searchRes', {searchText: lineName});
                    }

                    $scope.clearSearchText = function() {
                        $scope.searchContext.searchText = null;
                        $scope.searchContext.keyUpToSearch = false;
                    }

                    //清空查询历史事件
                    $scope.delSearchConfirm = function() {
                        $ionicPopup.confirm({
                            title: "清空搜索记录",
                            template: "确认清空全部搜索记录吗？",
                            cancelText: "取消",
                            okText: "确定",
                            okType: "button-balanced"
                        }).then(function(res) {
                            if (res) {
                                localStorageService.set("searchHistory", null);
                                $state.reload();
                                console.log("clear all histroy!");
                            } else {
                                console.log("clear all histroy has been canceled!");
                            }
                        })
                    }


                }])

})();